package com.example.springmvcdemo;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;

@RestController
public class ResponseEntityExample {

    @RequestMapping("/responseEntityExample")
    public ResponseEntity<String> responseEntityExample() {
        // 创建自定义响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Custom-Header", "CustomValue");

        // 返回带有自定义状态码、头部和内容的响应
        return new ResponseEntity<>(
                "响应内容",  // 响应体
                headers,    // 响应头
                HttpStatus.OK // 状态码
        );
    }


    @RequestMapping("/constructorExample")
    public ResponseEntity<String> constructorExample() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Header-Name", "Header-Value");

        return new ResponseEntity<>(
                "响应体内容",
                headers,
                HttpStatus.CREATED
        );
    }


    @RequestMapping("/staticMethodExample")
    public ResponseEntity<String> staticMethodExample() {
        return ResponseEntity
                .status(HttpStatus.OK) // 设置状态码
                .header("Custom-Header", "Value","MyHeader","MyHeaderValue") // 添加响应头
                .body("响应体内容"); // 设置响应体
    }

    @RequestMapping("/convenienceMethods")
    public ResponseEntity<String> convenienceMethods() {
        // 常用的便捷方法
        return ResponseEntity.ok("成功响应"); // 200 OK

        // 其他便捷方法示例：
//        return ResponseEntity.created(uri).body("资源已创建"); // 201 Created
//         return ResponseEntity.accepted().body("请求已接受"); // 202 Accepted
//         return ResponseEntity.noContent().build(); // 204 No Content
//         return ResponseEntity.badRequest().body("请求错误"); // 400 Bad Request
//         return ResponseEntity.notFound().build(); // 404 Not Found
    }


    @RequestMapping("/customHeaders")
    public ResponseEntity<String> customHeaders() {
        // 创建HttpHeaders对象
        HttpHeaders headers = new HttpHeaders();

        // 添加自定义头部（可以添加多个相同名称的头部）
        headers.add("Custom-Header", "Value1");
        headers.add("Custom-Header", "Value2");

        // 设置Content-Type头部（会覆盖已存在的值）
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 设置单个头部值（会覆盖已存在的值）
        headers.set("Another-Header", "SingleValue");

        return new ResponseEntity<>("响应内容", headers, HttpStatus.OK);
    }
}